package com.dongdongshop.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.pojo.*;
import com.dongdongshop.service.*;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
@com.alibaba.dubbo.config.annotation.Service
public class ItemPageServiceImpl implements ItemPageServiceI {

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Reference
    private TbGoodsServiceI tbGoodsServiceI;

    @Reference
    private TbGoodsDescServiceI tbGoodsDescServiceI;


    @Reference
    private TbItemCatServiceI tbItemCatServiceI;


    @Reference
    private TbItemServiceI tbItemServiceI;

    @Value("${freemarker.pageDir}")
    private String pageDir;

    @Override
    public void itemPage(Long goodsId) {

        //加载配置
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        FileWriter fileWriter = null;
        //创建模板
        try {
            Template template = configuration.getTemplate("item.ftl");
            //创建模型数据对象
            Map map = new HashMap();

            //查询goods表
            TbGoods tbGoods = tbGoodsServiceI.findGoodsById(goodsId);
            //查询TbGoodsDesc表
            TbGoodsDesc tbGoodsDesc =  tbGoodsDescServiceI.findGoodsDescByGoodsId(goodsId);
            map.put("goods",tbGoods);
            map.put("goodsDesc",tbGoodsDesc);


            //根据goods中的三个分类的id 查询出三级分类
            // 1
           TbItemCat  t =  tbItemCatServiceI.findtbItemCatByName(tbGoods.getCategory1Id());
            map.put("tbSpec",t);

            //2
            TbItemCat t1  = tbItemCatServiceI.findtbItemCatByNames(tbGoods.getCategory2Id());
            map.put("tbSpec1",t1);

            //3
            TbItemCat t2  = tbItemCatServiceI.findtbItemCatByNamess(tbGoods.getCategory3Id());
            map.put("tbSpec2",t2);



            //查询sku 列表(item)
            List<TbItem> itemList =  tbItemServiceI.selectItemList(tbGoods.getId());
            map.put("itemList",itemList);

            //创建输出流对象
            fileWriter = new FileWriter(pageDir + goodsId + ".html");
            template.process(map,fileWriter);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(fileWriter != null){
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
